MAKEFLAGS="-s " 

Tmp =    $(HOME)/tmp
What=    $(shell basename $(PWD))
Profile= $(Tmp)/awkprof.out
Vars=    $(Tmp)/awkvars.out
Time=    "%U sec(s) user %S system sec(s) "
Seed=    $(shell bash bin/rand)
Lib=     lib/
Built=   $(Opt)/auk/lib/
Doc=     $(Opt)/auk/doc/

Dirs=    var $(Tmp) lib bin $(Opt)/tmp $(Built) $(Doc)

#building awk
Opt=     $(HOME)/opt
GawkTar= http://ftp.gnu.org/gnu/gawk/$(GawkVer).tar.xz
GawkOpt= $(Opt)/gawk
Gawk=    $(GawkOpt)/bin/pgawk
Pandoc=  $(HOME)/.cabal/bin/pandoc 
Go= $(Gawk) --dump-variables=/tmp/${USER}awkvars.out \
	    --profile=/tmp/${USER}awkprof.out \
                  -f $@.awk --source 'BEGIN { print "$@:",_$@(); }'; \
                   [ -f "tmp/${USER}awkvars.out" ] && \
                   egrep -v '[A-Z][A-Z]' /tmp/${USER}awkvars.out | \
	           sed 's/^/W> rogue local: /'

ready: dirs $(Gawk) $(Pandoc) awks markdowns htmls texs epubs pdfs

code : dirs $(Gawk) awks

$(Gawk): 
	bash bin/getgawk $(GawkTar) $(GawkVer)  $(Tmp) $(GawkOpt)

reset: 
	rm -f $(Built)*.awk $(Doc)*.html $(Doc)*.pdf $(Doc)*.md $(Doc)*.epub

Got=       $(shell ls $(Lib)*.auk)
Awks=      $(subst $(Lib),$(Built),$(subst .auk,.awk, $(Got)))
Epubs=     $(subst $(Lib),$(Doc),  $(subst .auk,.epub,$(Got)))
Htmls=     $(subst $(Lib),$(Doc),  $(subst .auk,.html,$(Got)))
Markdowns= $(subst $(Lib),$(Doc),  $(subst .auk,.md,  $(Got)))
Pdfs=      $(subst $(Lib),$(Doc),  $(subst .auk,.pdf, $(Got)))
Texs=      $(subst $(Lib),$(Doc),  $(subst .auk,.tex, $(Got)))

#building pandoc
$(Pandoc):; sudo bash bin/getpandoc

#building awks
awks:  dirs $(Awks)

$(Built)%.awk :  $(Lib)%.auk $(Tmp)/h.sed
	echo $@ 1>&2
	$(Gawk) -f bin/auk2awk.awk $< | sed -f $(Tmp)/h.sed > $@

Hs=$(shell ls lib/*.h)
$(Tmp)/h.sed : $(Hs)  etc/h2sed.awk
	rm -f $(Tmp)/h.all	
	$(foreach f, $(Hs), \
     (echo ""; cat $f ; echo "") >> $(Tmp)/h.all;  )	
	$(Gawk) -f etc/h2sed.awk $(Tmp)/h.all > $@

#building md
markdowns:  dirs $(Markdowns)

$(Doc)%.md : $(Lib)%.auk
	echo $@ 1>&2
	$(Gawk) -f bin/auk2md.awk $< > $@

#building html
Css=css1.css
htmls: $(Htmls)
	@cp etc/$(Css) $(Doc)$(Css)

$(Doc)%.html : $(Doc)%.md  
	echo $@ 1>&2
	cp etc/$(Css) $(Doc)$(Css)
	@$(Pandoc) -s -S --toc -c $(Css)  \
            --bibliography=my.bib \
            --highlight-style kate \
            --mathjax  $< -o  $@

#building tex
texs: $(Texs)

$(Doc)%.tex: $(Doc)%.md
	@echo $@ 1>&2
	$(Pandoc) --standalone \
            --template=etc/default.latex --mathml \
            --bibliography=my.bib -s $< -o $@
	sed -i -f etc/tex.sed  $@ 

#building pdfs
pdfs: $(Pdfs) 

Hide= -interaction batchmode
$(Doc)%.pdf: $(Doc)%.tex
	@echo $@ 1>&2
	pdflatex  --output-directory $(HOME)/tmp $<  
	cp $(HOME)/tmp/$(shell basename $@)  $@

#building epubs
epubs: $(Epubs)

$(Doc)%.epub: $(Doc)%.md
	@echo $@ 1>&2
	$(Pandoc) --mathjax --bibliography=my.bib $<  -o $@

#building dirs
dirs: 
	$(foreach d,$(Dirs),if [ ! -d $d ]; then mkdir -p $d; fi;)
